package com.lucasx.util;

import com.lucasx.entity.BasicDataNewOne;
import com.lucasx.entity.Direction;
import com.lucasx.entity.LishiWeather;
import com.lucasx.entity.Velocity;
import com.sun.deploy.model.Resource;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.io.Resources;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/10/7.
 * <p>
 * IO操作工具类
 */
public class FileUtil {

    /**
     * 以<b>Resource</b>的方式读取XML配置文件
     *
     * @param xmlPath
     * @param nodeName
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static Element readXml(String xmlPath, String nodeName) throws DocumentException, IOException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(Resources.getResourceAsStream(xmlPath));
        Node node = document.selectNodes("/wind/" + nodeName).get(0);

        return (Element) node;
    }

    /**
     * 获取XML配置文件中风速的列表
     *
     * @param element
     * @return
     */
    public static List<Velocity> getVelocityList(Element element) {
        List<Velocity> velocityList = new ArrayList<>();
        element.elementIterator().forEachRemaining(element1 -> {
            Velocity velocity = new Velocity(Short.parseShort(element1.attribute("level").getValue().trim()), Short
                    .parseShort
                            (element1.attribute("min").getValue().trim()),
                    Short.parseShort(element1.attribute("max").getValue().trim()));
            velocityList.add(velocity);
        });

        return velocityList;
    }

    /**
     * 获取XML配置文件中风向的列表
     *
     * @param element
     * @return
     */
    public static List<Direction> getDirectionList(Element element) {
        List<Direction> directionList = new ArrayList<>();
        element.elementIterator().forEachRemaining(element1 -> {
            Direction direction = new Direction(Short.parseShort(element1.attribute("no").getValue().trim()), Double
                    .parseDouble(element1.attribute("startAngle").getValue().trim()),
                    Double.parseDouble(element1.attribute("toAngle").getValue().trim()));
            directionList.add(direction);
        });

        return directionList;
    }

    /**
     * 将列表数据写出到CSV文件 DATA FROM <b>lishi.tianqi.com</b>
     *
     * @param lishiWeatherList
     * @param csvPath
     */
    public static void outCsv(List<LishiWeather> lishiWeatherList, String csvPath, boolean isKeepHeader) throws IOException {
        StringBuilder stringBuilder;

        if (true == isKeepHeader) {
            stringBuilder = new StringBuilder("日期,最低温度,最高温度,天气,风向,风力\r\n");
        } else {
            stringBuilder = new StringBuilder();
        }
        lishiWeatherList.forEach(lishiWeather -> {
            stringBuilder.append(lishiWeather.getDate()).append(",").append(lishiWeather.getMinTemprature()).append
                    (",").append(lishiWeather.getMaxTemprature()).append(",")
                    .append(lishiWeather.getClimate()).append(",").append(lishiWeather.getWindDirect()).append(",")
                    .append(lishiWeather.getWindForce()).append("\r\n");
        });
        FileUtils.writeStringToFile(new File(csvPath), stringBuilder.toString(), "GBK");

        System.out.println("CSV生成成功，请查阅~");
    }

    /**
     * 从CSV读取 LishiWeather对象，返回列表
     *
     * @param csvPath
     * @return
     */
    public static List<LishiWeather> readCsv(String csvPath) throws IOException {
        List<LishiWeather> lishiWeatherList = new ArrayList<>();
        Files.readAllLines(Paths.get(csvPath), Charset.forName("GBK")).forEach(s -> {
            String[] strings = s.split(",");
            LishiWeather lishiWeather = new LishiWeather(strings[0], Integer.parseInt(strings[2].trim()), Integer
                    .parseInt(strings[1].trim()), strings[3], strings[4], strings[5]);

            lishiWeatherList.add(lishiWeather);
        });

        return lishiWeatherList;
    }

    /**
     * @param basicDataNewOneList
     * @param csvPath
     * @apiNote unfinished!
     */
    public static void writeListIntoCsv(List<BasicDataNewOne> basicDataNewOneList, String csvPath) {
        if (!Files.exists(Paths.get(csvPath).getParent()) || Files.isDirectory(Paths.get(csvPath).getParent())) {

        }
    }
}
